<?php
/**
 * HTML文档
 *
 * @version $Id: IMintHTMLDocument.php 312 2008-04-23 16:29:38Z iwind $
 * @package util.mint.format
 */
class IMintHTMLDocument extends IObject implements IMintDocument {
	private $chars = array();
	
	private $xmlDeclaration  = null;
	
	/**
	 * Enter description here...
	 *
	 * @var DOMDocument
	 */
	private $domDocument;
	
	private $randomTagName;
	
	/**
	 * 构造
	 *
	 */
	public function __construct() {
		libxml_use_internal_errors(true);
		$this->domDocument = new DOMDocument();	
	}
	
	/**
	 * 从文本中取得DOMDocument
	 *
	 * @param string $text 文本
	 */
	public function load($text) {
		if ($text != "") {
			$length = strlen($text);
			for ($i=0; $i<$length; $i++) {
				if (ord($text{$i}) > 127) {//处理多字节字符
					$this->chars[$i] = IMintReplacement::add($text{$i}, "php");
				}
				else {
					$this->chars[$i] = $text{$i};
				}
			}
			$text = implode("", $this->chars);
			
			//如果没有<body>
			if (!preg_match("/<body.+>.*<\\/body>/is", $text)) {
				$this->randomTagName = uniqid("T");
				$text = "<" . $this->randomTagName . ">" . $text . "</" . $this->randomTagName . ">";
			}
			
			$this->domDocument->loadHtml($text);
		}
	}
	
	/**
	 * 将文档转换成字符串
	 *
	 * @return string
	 */
	public function __toString() {		
		foreach (libxml_get_errors() as $error) {
			if ($error->level >= LIBXML_ERR_FATAL) {
				throw new IMintException("html parse error '{$error->message}' occured on line {$error->line}", $error->code);
			}
			else {
				ILogger::debug("parse warning: {$error->message} on line {$error->line}");
			}
		}
		$html = $this->domDocument->saveHTML();
		if (!is_null($this->randomTagName)) {
			$match = array();
			preg_match("/<{$this->randomTagName}>(.*)<\\/{$this->randomTagName}>/is", $html, $match);
			return $match[1];
		}
		return $html;
	}
	
	/**
	 * 取得DOMDocument对象
	 *
	 * @return DOMDocument
	 */
	public function getDOMDocument() {
		return $this->domDocument;
	}
}


?>